package com.ecmwidgets.test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.io.StringReader;   
import java.io.IOException;
import java.io.StringReader;
import java.math.BigInteger;
import java.util.List;
import com.ibm.ecm.configmgr.app.acm.widgets.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

   
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.ibm.json.java.JSONObject;

public class RESTClient {
	
	public static final String ATOM_ID = "atom:id";
	public static final String ATOM_ENTRY = "atom:entry";
	public static final String ATOM_TITLE = "atom:title";
	public static final String BLANK_TEMPLATE = "Blank Template";
	public static final String CreatePage = "D:\\ws2\\Installer_REST\\src\\com\\ecmwidgets\\test\\CreatePage.xml";
	public static final String fragment = "D:\\ws2\\Installer_REST\\src\\com\\ecmwidgets\\test\\fragment.xml";
//	public static final String FVT_MAIN = "D:\\ws2\\Installer_REST\\src\\com\\ecmwidgets\\test\\FVT_Main.xml";
//	public static final String LAYOUT1 = "D:\\ws2\\Installer_REST\\src\\com\\ecmwidgets\\test\\Col1.xml";
	
//	public static void main(String[] args) throws Exception {
//		
//		String hostname = "9.181.141.82";
//		String port = "9443";
//		String uid = "administrator";
//		String pwd = "jessica";
////		System.out.println(isSpaceExist("9.181.141.82","9443","intgpeadmin","tester"));
////		System.out.println(isSpaceExist("9.181.141.82","9443","administrator","jessica"));
////		System.out.println(getSpaceIDByName(hostname,port,uid,pwd,"Test"));
//		
////		System.out.println(getTemplateIDByName(hostname,port,uid,pwd,BLANK_TEMPLATE));
////		String id = createSpace("9.181.141.87","9443","administrator","jessica","SpaceA");
////		deleteSpaceByID("9.181.141.82","9443","administrator","jessica",id);
////		deleteSpaceByName("9.181.141.82","9443","administrator","jessica","a6");
////		listPage(hostname,port,uid,pwd);
//		String id = createPage(hostname,port,uid,pwd,"xubo","PageE");
//		setPageLayout(hostname,port,uid,pwd,id,LAYOUT1);
//		addWidget(hostname,port,uid,pwd,id,FVT_MAIN);
//		
//	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static boolean isSpaceExist(String hostname,String port,String uid,String pwd) throws Exception {
		// TODO Auto-generated method stub

		String protocol = getProtocolByPort(port);
		RESTClient client = new RESTClient();
//		String restURL = "https://9.181.141.82:9443/mashuphub/atom?collection=widgets.iwidgetURL";
		String url = protocol + "://" + hostname + ":"+ port + "/mum/mycontenthandler?uri=space%3Acollection&aspect=ac&start=0&num=5";
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", hostname);
        prop.setProperty("PORT", port);
        prop.setProperty("USERNAME", uid);
        prop.setProperty("PASSWORD", pwd);
		RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
		util.init(prop);
        String body = util.executeGet(url);
        ArrayList<String> list = listSpace(body);
        for(String item:list){
        	System.out.println(item);
        }
        return (list.size()>0) ;

	}
	
	public static ArrayList<String> listPage(String hostname,String port,String uid,String pwd) throws Exception {

//		ArrayList<String> list = new ArrayList<String>();
		String protocol = getProtocolByPort(port);
		RESTClient client = new RESTClient();
//		String restURL = "https://9.181.141.82:9443/mashuphub/atom?collection=widgets.iwidgetURL";
		String url = protocol + "://" + hostname + ":"+ port + "/mum/mycontenthandler?uri=space%3Acollection&aspect=ac&start=0&num=5";
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", hostname);
        prop.setProperty("PORT", port);
        prop.setProperty("USERNAME", uid);
        prop.setProperty("PASSWORD", pwd);
		RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
		util.init(prop);
        String body = util.executeGet(url);
        ArrayList<String> list = listSpace(body);
        for(String item:list){
        	System.out.println(item);
        }
        return list ;

	}
	
	
	public static String getProtocolByPort(String port) throws Exception{
		String protocol = "http";
		int nPort = 0;
		try{
			nPort = Integer.parseInt(port);
		}catch(Exception e){
			throw new Exception("Invalid port: [port=" + port + "]");
		}
		if(nPort>=9443){
			protocol = "https";
		}
		return protocol;
	}

	public static String getTemplateIDByName(String hostname,String port,String uid,String pwd,String templateName) throws Exception {
		// TODO Auto-generated method stub

		String protocol = getProtocolByPort(port);		RESTClient client = new RESTClient();
//		String restURL = "https://9.181.141.82:9443/mashuphub/atom?collection=widgets.iwidgetURL";
//		String url = protocol + "://" + hostname + ":"+ port + "/mum/mycontenthandler?uri=template%3Acollection&aspect=ac&start=0&num=5";
		String url = protocol + "://" + hostname + ":"+ port + "/mum/mycontenthandler?uri=template%3Acollection";
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", hostname);
        prop.setProperty("PORT", port);
        prop.setProperty("USERNAME", uid);
        prop.setProperty("PASSWORD", pwd);
		RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
		util.init(prop);
		
		
        String body = util.executeGet(url);
        
		Element   root   =   getRoot(body);		
		NodeList   nl   =   root.getElementsByTagName(ATOM_ENTRY);
		for(int i=0;i<nl.getLength();i++){
			Element ele = (Element) nl.item(i);
			Element title = (Element) (ele.getElementsByTagName(ATOM_TITLE).item(0));
			System.out.println(title.getTextContent());
			String tempName = title.getTextContent();
			if(tempName.equals(templateName)){
				Element id = (Element) (ele.getElementsByTagName(ATOM_ID).item(0));
				String tempID = id.getTextContent();
				tempID = tempID.replaceAll("template:id:", "");
				System.out.println(tempID);
				return tempID;
			}
		}
        return "" ;
	}


	public static String getSpaceIDByName(String hostname,String port,String uid,String pwd,String spaceName) throws Exception {
		// TODO Auto-generated method stub

		boolean more = true;
		int start = 0;
		int length = 5;
		
		String protocol = getProtocolByPort(port);		RESTClient client = new RESTClient();
//		String restURL = "https://9.181.141.82:9443/mashuphub/atom?collection=widgets.iwidgetURL";
		while(more){
//			String url = protocol + "://" + hostname + ":"+ port + "/mum/mycontenthandler?uri=Space%3Acollection&aspect=ac&start=0&num=5";
			String url = protocol + "://" + hostname + ":"+ port + "/mum/mycontenthandler?uri=Space%3Acollection&aspect=ac&start=" + start + "&num=" + length;
	        Properties prop = new Properties();
	        prop.setProperty("HOSTNAME", hostname);
	        prop.setProperty("PORT", port);
	        prop.setProperty("USERNAME", uid);
	        prop.setProperty("PASSWORD", pwd);
			RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
			util.init(prop);
	        String body = util.executeGet(url);
	        
			Element   root   =   getRoot(body);
			
			NodeList   nl   =   root.getElementsByTagName(ATOM_ENTRY);
			for(int i=0;i<nl.getLength();i++){
				Element ele = (Element) nl.item(i);
				Element title = (Element) (ele.getElementsByTagName(ATOM_TITLE).item(0));
				System.out.println(title.getTextContent());
				String tempName = title.getTextContent();
				if(tempName.equals(spaceName)){
					Element id = (Element) (ele.getElementsByTagName(ATOM_ID).item(0));
					String tempID = id.getTextContent();
					tempID = tempID.replaceAll("space:id:", "");
					System.out.println(tempID);
					return tempID;
				}
			}			
			if(nl.getLength()==length){
				more = true;
				start = start + length;
			}else{
				more = false;
			}
		}
        return "" ;
	}

	public static String getSpaceIDByName(String resultXML,String spaceName) throws Exception {

		Element   root   =   getRoot(resultXML);		
		NodeList   nl   =   root.getElementsByTagName(ATOM_ENTRY);
		for(int i=0;i<nl.getLength();i++){
			Element ele = (Element) nl.item(i);
			Element title = (Element) (ele.getElementsByTagName(ATOM_TITLE).item(0));
			System.out.println(title.getTextContent());
			String tempName = title.getTextContent();
			if(tempName.equals(spaceName)){
				Element id = (Element) (ele.getElementsByTagName(ATOM_ID).item(0));
				String tempID = id.getTextContent();
				tempID = tempID.replaceAll("space:id:", "");
				System.out.println(tempID);
				return tempID;
			}
		}
        return "" ;
	}

	public static Element getRoot(String xml) throws Exception{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		StringReader sr = new StringReader(xml);
		InputSource is = new InputSource(sr);
		Document doc = db.parse(is); 
		Element   root   =   doc.getDocumentElement(); 
		return root;
	}
	
//	public static InputStream String2InputStream(String str){
//	    ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
//	    return stream;
//	}

	public static ArrayList<String> listSpace(String xmlString) throws ParserConfigurationException, SAXException, IOException{
		ArrayList<String> list = new ArrayList<String> ();
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		DocumentBuilder db=dbf.newDocumentBuilder();
		StringReader sr=new StringReader(xmlString);
		InputSource is=new InputSource(sr);
		Document doc=db.parse(is); 
		Element   root   =   doc.getDocumentElement(); 
		NodeList   nl   =   root.getChildNodes(); 
//		System.out.println(nl.getLength());
		for(int i=0;i<nl.getLength();i++){
			Node node = nl.item(i);
//			System.out.println(node.getNodeName());
			if(node.getNodeName().equals(ATOM_ENTRY)){
				NodeList nl2 =   node.getChildNodes();
//				System.out.println(nl2.getLength());
				String spaceID = "";
				String spaceName = "";
				for(int j=0;j<nl2.getLength();j++){
					Node node2 = nl2.item(j);
//					System.out.println(node2.getNodeName());
					if(node2.getNodeName().equals(ATOM_ID)){
						spaceID = node2.getTextContent().replaceAll("space:id:", "");
//						System.out.println("Space   ID:" + spaceID);						
					}
					if(node2.getNodeName().equals(ATOM_TITLE)){
						spaceName = node2.getTextContent();
//						System.out.println("Space NAME:" + spaceName);						
					}
				}
				list.add(spaceID+"-"+spaceName);
			}
//			System.out.println(nl.item(i).getTextContent());
		}
		return list;
	}

	public static String getAtomID(String xmlString,String title,String prefix) throws Exception{
		
		Element   root   =   getRoot(xmlString);		
		NodeList   nl   =   root.getElementsByTagName(ATOM_ENTRY);
		for(int i=0;i<nl.getLength();i++){
			Element ele = (Element) nl.item(i);
			Element titleEle = (Element) (ele.getElementsByTagName(ATOM_TITLE).item(0));
			System.out.println(titleEle.getTextContent());
			String tempName = titleEle.getTextContent();
			if(tempName.equals(title)){
				Element id = (Element) (ele.getElementsByTagName(ATOM_ID).item(0));
				String tempID = id.getTextContent();
				tempID = tempID.replaceAll(prefix, "");
				System.out.println(tempID);
				return tempID;
			}
		}
        return "" ;
	}

	
	public static String createSpace(String hostname,String port,String uid,String pwd,String spaceName) throws Exception{
//			contenthandler?uri=template:collection
			//application favorites entry point - context 'wps' may be different on your system
			//Create Space,
			HttpClient client = new HttpClient();
			client.getState().setCredentials(
				new AuthScope(hostname, Integer.parseInt(port),AuthScope.ANY_REALM),
				new UsernamePasswordCredentials(uid, pwd));
			
			HttpClientParams params = new HttpClientParams();
			params.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
			client.setParams(params);
			
			String protocol = getProtocolByPort(port);
			PostMethod postMethod = new PostMethod(protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=space:collection");
			postMethod.setDoAuthentication(true);
			Header mtHeader = new Header();
			mtHeader.setName("content-type");
			mtHeader.setValue("application/atom+xml");
			postMethod.addRequestHeader(mtHeader);
			
			String str ="<atom:entry xmlns:atom=\"http://www.w3.org/2005/Atom\"><atom:id>id:0</atom:id><atom:title>New Space</atom:title><atom:updated>Thu, 15 Apr 2010 10:01:46 GMT</atom:updated><atom:content type=\"application/xml\"><ca:application xmlns:ca=\"http://www.ibm.com/xmlns/prod/composite-applications/v1.0\" ca:template-id=\"@TEMPLATEID\"><ca:title xml:lang=\"en\">@SPACENAME</ca:title><ca:description xml:lang=\"en\"></ca:description><ca:meta-data ca:name=\"{http://www.ibm.com/xmlns/prod/lotus/mashups/v1.0/extensions}iconUrl\">/mum/images/spaceicons/icon-01.gif</ca:meta-data></ca:application></atom:content></atom:entry>";
			str = str.replaceAll("@TEMPLATEID", getTemplateIDByName(hostname,port,uid,pwd,BLANK_TEMPLATE));
			str = str.replaceAll("@SPACENAME", spaceName);
			System.out.println(str);
			RequestEntity requestEntity = new StringRequestEntity(str);
			postMethod.setRequestEntity(requestEntity);
			postMethod.setDoAuthentication(true);	
			
			client.executeMethod(postMethod);
			
			System.out.println("Status code: " + postMethod.getStatusCode());
			Header contentTypeHeader = postMethod.getResponseHeader("content-type");
			//System.out.println("Mimetype: " + contentTypeHeader.getValue());
			System.out.println("Response: " + postMethod.getResponseBodyAsString());
			String resultXML = postMethod.getResponseBodyAsString();
			postMethod.releaseConnection(); 
			String spaceID = getSpaceIDByName(resultXML,spaceName);
			return spaceID;
	}

	public static boolean deleteSpaceByID(String hostname,String port,String uid,String pwd,String spaceID) throws Exception{
			HttpClient client = new HttpClient();
			client.getState().setCredentials(
				new AuthScope(hostname, Integer.parseInt(port),AuthScope.ANY_REALM),
				new UsernamePasswordCredentials(uid, pwd));
			
			HttpClientParams params = new HttpClientParams();
			params.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
			client.setParams(params);
			
			String protocol = getProtocolByPort(port);
//			String url = "http://" + hostname + ":" + port + "/mum/mycontenthandler?uri=space%3Aid%3A@SPACEID&update=replace";
			String url = "https://" + hostname + ":" + port + "/mum/mycontenthandler?uri=space%3Aid%3A@SPACEID";
//			contenthandler?uri=space:id:<space-id>

			url = url.replaceAll("@SPACEID", spaceID);
			System.out.println(url);
			HttpMethod httpMethod = new DeleteMethod(url);
//			https://9.181.141.82:9443/mum/mycontenthandler?uri=space%3Aid%3A09B58D5211D16F9429F208BDB5EB9F00003D&update=replace			
			httpMethod.setDoAuthentication(true);
			client.executeMethod(httpMethod);
			System.out.println("Status code: " + httpMethod.getStatusCode());
//			Header contentTypeHeader = httpMethod.getResponseHeader("content-type");
//			System.out.println("Mimetype: " + contentTypeHeader.getValue());
//			System.out.println("Response: " + httpMethod.getResponseBodyAsString());
			httpMethod.releaseConnection(); 
			return true;
		
	}

	public static boolean deleteSpaceByName(String hostname,String port,String uid,String pwd,String spaceName) throws Exception{
		HttpClient client = new HttpClient();
		client.getState().setCredentials(
			new AuthScope(hostname, Integer.parseInt(port),AuthScope.ANY_REALM),
			new UsernamePasswordCredentials(uid, pwd));
		
		HttpClientParams params = new HttpClientParams();
		params.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
		client.setParams(params);
		
		String protocol = getProtocolByPort(port);
//		String url = "http://" + hostname + ":" + port + "/mum/mycontenthandler?uri=space%3Aid%3A@SPACEID&update=replace";
		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=space%3Aid%3A@SPACEID";
//		contenthandler?uri=space:id:<space-id>

		String spaceID = getSpaceIDByName(hostname, port, uid,pwd, spaceName);
		url = url.replaceAll("@SPACEID", spaceID);
		System.out.println(url);
		HttpMethod httpMethod = new DeleteMethod(url);
		httpMethod.setDoAuthentication(true);
		client.executeMethod(httpMethod);
		System.out.println("Status code: " + httpMethod.getStatusCode());
		httpMethod.releaseConnection(); 
		return true;
	}

	public static String createPage(String hostname,String port,String uid,String pwd,String spaceName, String pageName) throws Exception{
				
	
		String protocol = getProtocolByPort(port);
		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=nm%3Acollection&aspect=ac&aspect=ca&rep=full";
		System.out.println(url);		
		
		String spaceID = getSpaceIDByName(hostname,port,uid,pwd,spaceName);
		
//		String key1="b34318b3";  
		BigInteger sID = new BigInteger(spaceID, 16);
		BigInteger s1 = new BigInteger("1", 16);
		sID = sID.add( s1 );
		String newID = sID.toString(16);
		for(int i=0;i<spaceID.length() - newID.length(); i++){
			newID = "0" + newID;
		}
		newID = newID.toUpperCase();
		System.out.println(newID);
//		System.out.println(str);
		
		String str = xml2str(CreatePage);
//		String str ="<atom:entry xmlns:atom=\"http://www.w3.org/2005/Atom\"><atom:id>id:0</atom:id><atom:title>New Space</atom:title><atom:updated>Thu, 15 Apr 2010 10:01:46 GMT</atom:updated><atom:content type=\"application/xml\"><ca:application xmlns:ca=\"http://www.ibm.com/xmlns/prod/composite-applications/v1.0\" ca:template-id=\"@TEMPLATEID\"><ca:title xml:lang=\"en\">@SPACENAME</ca:title><ca:description xml:lang=\"en\"></ca:description><ca:meta-data ca:name=\"{http://www.ibm.com/xmlns/prod/lotus/mashups/v1.0/extensions}iconUrl\">/mum/images/spaceicons/icon-01.gif</ca:meta-data></ca:application></atom:content></atom:entry>";
		String fragmentID = getFragmentID(hostname,port,uid,pwd);
		str = str.replaceAll("@PAGENAME", pageName);
		str = str.replaceAll("@SPACEID", newID);
		str = str.replaceAll("@FRAGMENTID", fragmentID);
		str = str.replaceAll("@PROTOCAL", protocol);
		str = str.replaceAll("@HOSTNAME", hostname);
		str = str.replaceAll("@PORT", port);
				
		System.out.println(str);
		
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", hostname);
        prop.setProperty("PORT", port);
        prop.setProperty("USERNAME", uid);
        prop.setProperty("PASSWORD", pwd);
		RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
		util.init(prop);
		
		
        String body = util.executePost(url, str);
        String pageID = getAtomID(body,pageName,"nm:id:");
        System.out.println(pageID);
        
//        https://9.181.141.82:9443/mum/mycontenthandler?uri=fragment-media%3A%2F09B58D5289291D6ACA96C268AC183600002B%2Findex.html
        return pageID;
//		System.out.println("Status code: " + postMethod.getStatusCode());
//		Header contentTypeHeader = postMethod.getResponseHeader("content-type");
		//System.out.println("Mimetype: " + contentTypeHeader.getValue());
//		System.out.println("Response: " + postMethod.getResponseBodyAsString());
//		String resultXML = postMethod.getResponseBodyAsString();
//		postMethod.releaseConnection(); 
//		String spaceID = getSpaceIDByName(resultXML,spaceName);
//		return spaceID;
	}

	public static String createPage(String hostname,String port,String uid,String pwd,String spaceName, String pageName, String xml1, String xml2, String xml3) throws Exception{
		String page1ID = RESTClient.createPage(hostname,port,uid,pwd,spaceName,pageName);
		RESTClient.setPageLayout(hostname,port,uid,pwd,page1ID,xml1);
		RESTClient.setPageLayout(hostname,port,uid,pwd,page1ID,xml2);
		RESTClient.addWidget(hostname,port,uid,pwd,page1ID,xml3);
		return page1ID;
	}

	public static String addWidget(String hostname,String port,String uid,String pwd,String pageID,String pageXMLFileName) throws Exception{
		
		
		String protocol = getProtocolByPort(port);
//		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=nm%3Acollection&aspect=ac&aspect=ca&rep=full";
		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=fragment-media%3A" + pageID + "%2Findex.html";
		System.out.println(url);		
				
		String str = xml2str(pageXMLFileName);
//		String str ="<atom:entry xmlns:atom=\"http://www.w3.org/2005/Atom\"><atom:id>id:0</atom:id><atom:title>New Space</atom:title><atom:updated>Thu, 15 Apr 2010 10:01:46 GMT</atom:updated><atom:content type=\"application/xml\"><ca:application xmlns:ca=\"http://www.ibm.com/xmlns/prod/composite-applications/v1.0\" ca:template-id=\"@TEMPLATEID\"><ca:title xml:lang=\"en\">@SPACENAME</ca:title><ca:description xml:lang=\"en\"></ca:description><ca:meta-data ca:name=\"{http://www.ibm.com/xmlns/prod/lotus/mashups/v1.0/extensions}iconUrl\">/mum/images/spaceicons/icon-01.gif</ca:meta-data></ca:application></atom:content></atom:entry>";
//		String fragmentID = getFragmentID(hostname,port,uid,pwd);
//		str = str.replaceAll("@PAGENAME", pageName);
//		str = str.replaceAll("@SPACEID", newID);
//		str = str.replaceAll("@FRAGMENTID", fragmentID);
		str = str.replaceAll("@PROTOCAL", protocol);
		str = str.replaceAll("@HOSTNAME", hostname);
		str = str.replaceAll("@PORT", port);
		str = str.replaceAll("<root>", "");		
		str = str.replaceAll("</root>", "");		
		String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		str = str.substring(header.length());
//		str = str.replaceAll("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
		System.out.println(str);
		
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", hostname);
        prop.setProperty("PORT", port);
        prop.setProperty("USERNAME", uid);
        prop.setProperty("PASSWORD", pwd);
		RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
		util.init(prop);
		
		
        String body = util.executePut(url, str);
        return body;
	}

	public static String setPageLayout(String hostname,String port,String uid,String pwd,String pageID,String layoutXMLFileName) throws Exception{
		
		
		String protocol = getProtocolByPort(port);
//		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=nm%3Acollection&aspect=ac&aspect=ca&rep=full";
//		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=fragment-media%3A" + pageID + "%2Findex.html";
		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=fragment%3Aid%3A" + pageID;
		System.out.println(url);		
				
		String str = xml2str(layoutXMLFileName);
//		String str ="<atom:entry xmlns:atom=\"http://www.w3.org/2005/Atom\"><atom:id>id:0</atom:id><atom:title>New Space</atom:title><atom:updated>Thu, 15 Apr 2010 10:01:46 GMT</atom:updated><atom:content type=\"application/xml\"><ca:application xmlns:ca=\"http://www.ibm.com/xmlns/prod/composite-applications/v1.0\" ca:template-id=\"@TEMPLATEID\"><ca:title xml:lang=\"en\">@SPACENAME</ca:title><ca:description xml:lang=\"en\"></ca:description><ca:meta-data ca:name=\"{http://www.ibm.com/xmlns/prod/lotus/mashups/v1.0/extensions}iconUrl\">/mum/images/spaceicons/icon-01.gif</ca:meta-data></ca:application></atom:content></atom:entry>";
//		String fragmentID = getFragmentID(hostname,port,uid,pwd);
//		str = str.replaceAll("@PAGENAME", pageName);
		str = str.replaceAll("@PAGEID", pageID);
//		str = str.replaceAll("@FRAGMENTID", fragmentID);
		str = str.replaceAll("@PROTOCAL", protocol);
		str = str.replaceAll("@HOSTNAME", hostname);
		str = str.replaceAll("@PORT", port);	
		String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		str = str.substring(header.length());
//		str = str.replaceAll("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
		System.out.println(str);
		
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", hostname);
        prop.setProperty("PORT", port);
        prop.setProperty("USERNAME", uid);
        prop.setProperty("PASSWORD", pwd);
		RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
		util.init(prop);
		
		
        String body = util.executePut(url, str);
        return body;
	}

	public static String getFragmentID(String hostname,String port,String uid,String pwd) throws Exception{
				
		String protocol = getProtocolByPort(port);
		String url = protocol + "://" + hostname + ":" + port + "/mum/mycontenthandler?uri=fragment%3Acollection";
		System.out.println(url);
		
		String str = xml2str(fragment);
		System.out.println(str);
				
        Properties prop = new Properties();
        prop.setProperty("HOSTNAME", hostname);
        prop.setProperty("PORT", port);
        prop.setProperty("USERNAME", uid);
        prop.setProperty("PASSWORD", pwd);
		RESTUtilOnATOM util =(RESTUtilOnATOM) RESTUtil.getATOMUtil();
		util.init(prop);
		
        String body = util.executePost(url, str);
        String id = getAtomID(body,"No Title Defined","fragment:id:");
        return id;
        
	}

	public static String xml2str(String fileName) throws Exception{
		XMLUtils util = new XMLUtils(fileName);
		Document doc = util.getDocument();
		StringWriter output = new StringWriter();
		TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(output));
		System.out.println(output.toString());
		return output.toString();
	}
}
